﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeddingEventManagementApp.Models;
using WeddingEventManagement_API;
using System.Web.Security;

namespace WeddingEventManagementApp.Controllers
{
    public class InvoiceController : BaseController
    {
        private InvoiceManager invoiceManager;

        /// <summary>
        /// Public constructor
        /// </summary>
        public InvoiceController()
        {
            invoiceManager = new InvoiceManager();
        }

        /// <summary>
        /// Returns total for invoice after payments applied
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult GetInvoiceTotalJson(int id)
        {
            var invTotal = new { total = invoiceManager.GetRemainingBalanceForInvoice(id).ToString("c") };

            return Json(invTotal, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Create(int id)
        {
            try
            {
                EventManager eventManager = new EventManager();
                Event evt = eventManager.GetEvent(id);

                // Get package for event
                Package eventPackage = evt.Package;
                // Create Invoice Line for Package
                List<InvoiceItem> items = new List<InvoiceItem>();
                if(eventPackage.BasePrice > 0)
                    items.Add(new InvoiceItem() { Name = eventPackage.PackageType, Description = eventPackage.Description, Qty=1, Price = eventPackage.BasePrice });
                
                //add flower and decor items
                if (evt.Flowers.HasValue && evt.Flowers.Value)
                {
                    items.Add(new InvoiceItem() { 
                        Name = "Flowers",
                        Description = "Flower Budget",
                        Qty = 1,
                        Price = evt.FlowersBudget.Value
                    });
                }
                if (evt.Decor.HasValue && evt.Decor.Value)
                {
                    items.Add(new InvoiceItem() { 
                        Name = "Decor",
                        Description = "Decor Budget",
                        Qty = 1,
                        Price = evt.DecorBudget.Value
                    });
                }

                // Create Invoice
                int invoiceID = invoiceManager.CreateInvoice
                    (
                        id, 
                        Utility.GetUserID(User.Identity.Name), 
                        DateTime.UtcNow.AddDays(30), 
                        items,
                        null
                    );

                return RedirectToAction("Index", "Invoice",  new { id = invoiceID });
            }
            catch (Exception)
            {
                this.ShowMessage("Error Creating Invoice", MessageType.Error);
                throw;
            }
        }

        /// <summary>
        /// Get all the payments in JSON format
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult GetPaymentsJson(int id)
        {
            var payments =
                from p in invoiceManager.GetPayments(id)
                select new 
                {   Amount = p.Amount.ToString("c"), 
                    Date = p.DateTime.ToShortDateString(), 
                    PaymentType = p.PaymentType, 
                    Creator = Membership.GetUser(p.CreatorUserID).UserName,
                    PaymentID = p.PaymentID,
                    InvoiceID = p.InvoiceID
                };

            return Json(payments, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Get all the types of payments in JSON format
        /// </summary>
        /// <returns></returns>
        public JsonResult GetPaymentTypesJson()
        {
            var paymentTypes =
                from t in invoiceManager.GetPaymentTypes()
                select new { type = t };

            return Json(paymentTypes, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Delete a particular payment from the system
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeletePayment(int id)
        {
            int invoiceID = invoiceManager.GetInvoiceIDForPayment(id);
            invoiceManager.DeletePayment(id);

            return GetPaymentsJson(invoiceID);
        }

        /// <summary>
        /// Add a new payment to the system
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddPayment(Payment_VM model)
        {
            try
            {
                DateTime date = DateTime.Parse(model.Date);
                invoiceManager.AddPayment
                (
                    model.InvoiceID, 
                    model.Amount, 
                    model.PaymentType, 
                    Utility.GetUserID(Membership.GetUser().UserName), 
                    DateTime.UtcNow
                );
            }
            catch
            {
                ShowMessage("Error Adding Payment", MessageType.Error);
            }

            // if it's coming from the event details page don't redirect to the wrong area
            if (model.EventID.HasValue)
            {
                return RedirectToAction("Details", "Event", new { id = model.EventID.Value });
            }
            
            return Redirect(Url.Action("Details", "Client", new { id = model.ClientID }) + "#tab3");
        }

        /// <summary>
        /// Retrieve invoice for editing
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Index(int id)
        {
            var model = invoiceManager.GetInvoice(id);

            // round decimal to 2 places
            model.InvDeliveryCharge = Decimal.Round(model.InvDeliveryCharge, 2);

            return View("Invoice", model);
        }

        /// <summary>
        /// Save Invoice
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(Invoice model)
        {
            try
            {

                model.UpdateUserID = Utility.GetUserID(User.Identity.Name);
                invoiceManager.SaveInvoice(model);

                ShowMessage("Saved Succesfully", MessageType.Success);
                return RedirectToAction("Index", new { id = model.InvoiceID });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("", ex);
            }

            return View("Invoice", model);
        }
    }
}
